package com.zhang.abandon;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class HttpClientService {

//    public static void main(String[] args){
//        System.out.println(new HttpClientService().getHtml("https://www.bilibili.com"));
//    }

    /**
     * 返回HTML
     * @param url
     * @return
     */
    public String getHtml(String url){
        String html;
        //建立HttpClient类
        CloseableHttpClient httpclient = HttpClients.createDefault();

        //设置代理IP
        //HttpHost proxy = new HttpHost("218.93.117.87",8080);
        //设置超时时间
       // RequestConfig config = RequestConfig.custom().setProxy(proxy).setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(5000).build();
        RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(5000).build();
        //设置请求信息
        HttpGet getMethod = new HttpGet(url);
        //添加请求头
        getMethod.addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2");
        getMethod.setConfig(config);

        BufferedReader reader = null; //读取html的流
        HttpResponse response; //响应
        try {
            //获得响应
            response = httpclient.execute(getMethod);
            //响应体
            HttpEntity entity = response.getEntity();
            //建立一个读取流
            reader = new BufferedReader(new InputStreamReader(entity.getContent()));
            //读取html
            String buff;
            StringBuilder sb = new StringBuilder();
            while((buff = reader.readLine()) != null){
                sb.append(buff);
            }
            html = sb.toString();
            System.out.println(html);
            return html;
        } catch (ClientProtocolException e) {
            System.out.println("【错误】连接异常");
            return null;
        } catch (IOException e) {
            System.out.println("【错误】读取异常");
            return null;
        }finally{
            try {
                httpclient.close();
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                System.out.println("关闭资源失败");
            }
        }
    }
}